<?php
/**
*
* @package FullAljax
* @version 0.8.0
* @copyright (c) 2008 Alek$
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
* Minimum Requirement: PHP 4.3.3
*/

// Do bsic initialization of phpBB and ajax libraries
define('IN_PHPBB', true);

$phpbb_root_path = './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

include($phpbb_root_path . 'includes/JsHttpRequest.' . $phpEx);
$JsHttpRequest =& new JsHttpRequest("utf-8");

include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin(false);
$auth->acl($user->data);
$user->setup();

// Obtain working mode
$mode = request_var('mode', '');

if( $mode == 'pm_check' )
{
	/**
	Basic checking of new PMs
	*/
	
	// Set CUP language file
	$user->setup('ucp');
	
	// Init variables
	$l_privmsgs_text = $l_privmsgs_text_unread = '';
	$s_privmsg_new = false;

	// Obtain number of new private messages if user is logged in
	if (isset($user->data['is_registered']) && $user->data['is_registered'])
	{
		if ($user->data['user_new_privmsg'])
		{
			// If there are any new PMs, set correct message about it.
			$l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
			$l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);

			// Mark PMs as notfied
			if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
			{
				$sql = 'UPDATE ' . USERS_TABLE . '
					SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
					WHERE user_id = ' . $user->data['user_id'];
				$db->sql_query($sql);

				$s_privmsg_new = true;
			}
			else
			{
				$s_privmsg_new = false;
			}
		}
		else
		{
			$l_privmsgs_text = $user->lang['NO_NEW_PM'];
			$s_privmsg_new = false;
		}

		$l_privmsgs_text_unread = '';

		// Get number of unread PMs
		if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
		{
			$l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
			$l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
		}
		
		// Prepare results for sending back to browser
		$_RESULT['pm_new'] = $l_privmsgs_text . ' (' . $user->format_date(time(), false, true) . ')';
		$_RESULT['pm_popup'] = $s_privmsg_new;
		$_RESULT['pm_ur'] = $l_privmsgs_text_unread;
	}
	else
	{
		$_RESULT = null;
	}
}
else if( $mode == 'pm_list' )
{
	/**
	Display list of new PMs
	*/
	
	// Obtain number of new private messages if user is logged in
	if (isset($user->data['is_registered']) && $user->data['is_registered'])
	{
		$sql = 'SELECT p.message_subject, p.message_time, p.msg_id, u.username, u.user_id, pt.folder_id
			FROM ' . USERS_TABLE . ' u, ' . PRIVMSGS_TABLE . ' p, ' . PRIVMSGS_TO_TABLE . ' pt
			WHERE pt.pm_new = 1
				AND pt.user_id = ' . $user->data['user_id'] . '
				AND pt.msg_id = p.msg_id
				AND pt.author_id = u.user_id
			ORDER BY p.message_time ASC';
		$result = $db->sql_query($sql);
		
		// Set template file
		$template->set_filenames(array(
			'body' => 'aljax_pm.html',
		));
		
		// Set template mode
		$template->assign_vars(array('S_PM_LIST' => true));
		
		// Display all new PMs
		while( $row = $db->sql_fetchrow($result) )
		{
			$template->assign_block_vars('pm_list_row', array(
				'SUBJECT'	=> $row['message_subject'],
				'AUTHOR'	=> $row['username'],
				'PROFILE'	=> append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u=' . $row['user_id']),
				'PM_LINK'	=> append_sid("{$phpbb_root_path}ucp.$phpEx", "i=pm&amp;mode=view&amp;p={$row['msg_id']}&amp;ref=1" ),
				'PM_ID'		=> $row['msg_id']
			));
		}
		
		// Output result
		$template->display('body');
	}
}
else if( $mode == 'pm_preview' )
{
	/**
	Display small preview of new PM
	*/
	
	// Obtain all information about PM if user is logged in
	if (isset($user->data['is_registered']) && $user->data['is_registered'])
	{
		$sql = 'SELECT p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.enable_sig, p.message_text, p.bbcode_bitfield, p.bbcode_uid
			FROM ' . PRIVMSGS_TABLE . ' p, ' . PRIVMSGS_TO_TABLE . ' pt
			WHERE p.msg_id = ' . request_var('id', -1) . '
				AND pt.user_id = ' . $user->data['user_id'] . '
				AND pt.msg_id = p.msg_id
			ORDER BY p.message_time ASC';
		$result = $db->sql_query($sql);
		
		$message_row = $db->sql_fetchrow($result);
		
		// Instantiate BBCode if need be
		if ($message_row['bbcode_bitfield'])
		{
			include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
			$bbcode = new bbcode($message_row['bbcode_bitfield']);
		}
		
		// Prepare message text
		$message = censor_text($message_row['message_text']);
		
		// Second parse bbcode here
		if ($message_row['bbcode_bitfield'])
		{
			$bbcode->bbcode_second_pass($message, $message_row['bbcode_uid'], $message_row['bbcode_bitfield']);
		}

		// Always process smilies after parsing bbcodes
		$message = bbcode_nl2br($message);
		$message = smiley_text($message);
		
		//Output parsed message into browser
		echo $message;
	}
}
else if($mode == 'quick_edit')
{
	/**
	Serve quick edit function
	*/
	
	// Set up language
	$user->setup('posting');
	
	// Init variables
	$_RESULT['success'] = false;
	
	$post_id = request_var('post_id',0);
	
	// Obtain all post information
	$sql = 'SELECT f.*, t.*, p.*, u.username, u.username_clean, u.user_sig, u.user_sig_bbcode_uid, u.user_sig_bbcode_bitfield
		FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . ' f, ' . USERS_TABLE . " u
		WHERE p.post_id = $post_id
			AND t.topic_id = p.topic_id
			AND u.user_id = p.poster_id
			AND f.forum_id = t.forum_id";
	
	$result = $db->sql_query($sql);
	$post_data = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	
	// Begin of number of checks if user can edit this post.
	if (!($user->data['is_registered'] && $auth->acl_gets('f_edit', 'm_edit', $post_data['forum_id'])))
	{
		exit($user->lang['USER_CANNOT_EDIT']);
	}
	
	if (($post_data['forum_status'] == ITEM_LOCKED
		|| (isset($post_data['topic_status'])
			&& $post_data['topic_status'] == ITEM_LOCKED))
		&& !$auth->acl_get('m_edit', $post_data['forum_id']))
	{
		exit(($post_data['forum_status'] == ITEM_LOCKED) ? 'FORUM_LOCKED' : 'TOPIC_LOCKED');
	}
	
	if (!$auth->acl_get('m_edit', $post_data['forum_id']))
	{
		if ($user->data['user_id'] != $post_data['poster_id'])
		{
			exit($user->lang['USER_CANNOT_EDIT']);
		}
	
		if (!($post_data['post_time'] > time() - ($config['edit_time'] * 60) || !$config['edit_time']))
		{
			exit($user->lang['CANNOT_EDIT_TIME']);
		}
	
		if ($post_data['post_edit_locked'])
		{
			exit($user->lang['CANNOT_EDIT_POST_LOCKED']);
		}
	}
	// End of number of checks if user can edit this post.
	
	// Set template file
	$template->set_filenames(array(
		'body' => 'aljax_quick_edit.html')
	);
	
	$_RESULT['success'] = true;
	
	if(isset($_REQUEST['submit']))
	{
		/**
		Serve saving edited post
		*/
		
		// Prepare text to saving into DB
		$content = utf8_normalize_nfc(request_var('content', '', true));
		
		$uid = $bitfield = $options = '';
		$allow_bbcode = $allow_urls = $allow_smilies = true;
		
		generate_text_for_storage($content, $uid, $bitfield, $options, $allow_bbcode, $allow_urls, $allow_smilies);
	
		$sql_array = array(
			'post_text'			=> $content,
			'bbcode_uid'		=> $uid,
			'bbcode_bitfield'   => $bitfield,
		);
	
		$sql = 'UPDATE ' . POSTS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_array) . " WHERE post_id = $post_id";
		$db->sql_query($sql);
		
		// Parse and display new post text
		$text = generate_text_for_display($content, $uid, $bitfield, 7);
		$template->assign_vars(array(
			'TEXT' => $text,
			'SAVE_POST' => true,
		));
	}
	else
	{
		/**
		Show quick edit form
		*/
		decode_message($post_data['post_text'], $post_data['bbcode_uid']);
		
		$template->assign_vars(array(
			'EDIT_POST' => true,
			'POST_TEXT' => $post_data['post_text'],
			'POST_ID'   => $post_id,
		));
	}
	
	// Output results
	$template->display('body');
}
else if($mode == 'quick_delete')
{
	/**
	Serve quick delete function
	*/
	
	// Set up language
	$user->setup('posting');
	
	// Init variables
	$_RESULT['success'] = true;
	
	$post_id = request_var('post_id',0);
	
	// Obtain post data
	$sql = 'SELECT f.*, t.*, p.*, u.username, u.username_clean, u.user_sig, u.user_sig_bbcode_uid, u.user_sig_bbcode_bitfield
		FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . ' f, ' . USERS_TABLE . " u
		WHERE p.post_id = $post_id
			AND t.topic_id = p.topic_id
			AND u.user_id = p.poster_id
			AND f.forum_id = t.forum_id";
	
	$result = $db->sql_query($sql);
	$post_data = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	
	// Check if such post exists
	if (!$post_data)
	{
		$_RESULT['success'] = false;
		exit($user->lang['NO_POST']);
	}

	// Init some additional variables to make our life more easy ;)
	$forum_id	= (!empty($post_data['forum_id'])) ? (int) $post_data['forum_id'] : (int) $forum_id;
	$topic_id	= (!empty($post_data['topic_id'])) ? (int) $post_data['topic_id'] : (int) $topic_id;
	$post_id	= (!empty($post_data['post_id'])) ? (int) $post_data['post_id'] : (int) $post_id;
	
	// Check if user can delete this post
	if (!($user->data['is_registered'] && $auth->acl_gets('f_delete', 'm_delete', $forum_id)))
	{
		$_RESULT['success'] = false;
		exit($user->lang['USER_CANNOT_DELETE']);
	}
	
	if (($post_data['forum_status'] == ITEM_LOCKED
		|| (isset($post_data['topic_status'])
			&& $post_data['topic_status'] == ITEM_LOCKED))
		&& !$auth->acl_get('m_delete', $post_data['forum_id']))
	{
		$_RESULT['success'] = false;
		exit(($post_data['forum_status'] == ITEM_LOCKED) ? 'FORUM_LOCKED' : 'TOPIC_LOCKED');
	}
	
	// Delete post
	handle_post_delete($forum_id, $topic_id, $post_id, $post_data);
}
else if($mode == 'check_username')
{
	/**
	Check if requested username is already taken
	*/
	
	// Include additional libraries
	include("$phpbb_root_path/includes/functions_user.$phpEx");
	
	// Sey up language
	$user->setup('ucp');
	
	// Init variables
	$_RESULT['success'] = true;
	
	$data = array(
		'username'	=> utf8_normalize_nfc(request_var('username', '', true)),
	);

	// Check if name is correct
	$error = validate_data($data, array(
		'username'	=> array(
			array('string', false, $config['min_name_chars'], $config['max_name_chars']),
			array('username', '')),
	));
	
	// Replace "error" strings with their real, localised form
	$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
	
	// Output result
	echo (sizeof($error)) ? implode('<br />', $error) : $user->lang['USER_NOT_FOUND'];
	
	if(sizeof($error))
		$_RESULT['success'] = false;
}
else if($mode == 'post_review')
{
	// Include additional libraries
	include("$phpbb_root_path/includes/functions_posting.$phpEx");
	
	// Set up language
	$user->setup('posting');
	
	// Init variables
	$_RESULT['success'] = false;
	
	$topic_id	= request_var('t', 0);
	$post_data['topic_cur_post_id']	= request_var('topic_cur_post_id', 0);
	
	// Obtain topic information
	$sql = 'SELECT f.*, t.*
		FROM ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . " f
		WHERE t.topic_id = $topic_id
			AND f.forum_id = t.forum_id";
	
	$result = $db->sql_query($sql);
	$post_data = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	
	// If replying/quoting and last post id has changed
	// give user option to continue submit or return to post
	// notify and show user the post made between his request and the final submit
	if ( $post_data['topic_cur_post_id'] != $post_data['topic_last_post_id'])
	{
		// Only do so if it is allowed forum-wide
		if ($post_data['forum_flags'] & FORUM_FLAG_POST_REVIEW)
		{
			// Set template file
			$template->set_filenames(array(
				'body' => 'aljax_review.html')
			);
			
			// Generate and output review
			if (topic_review($topic_id, $post_data['forum_id'], 'post_review', $post_data['topic_cur_post_id']))
			{
				$template->assign_var('S_AJAX_REVIEW', true);
				$_RESULT['topic_cur_post_id'] = $post_data['topic_last_post_id'];
				$_RESULT['success'] = true;
				$template->display('body');
			}
			
		}
	}
}
else if($mode == 'topic_preview')
{
	/**
	Preview topic
	*/
	
	// Set up language
	$user->setup('viewtopic');
	
	// Init variables
	$_RESULT['success'] = true;
	
	$topic_id = request_var('t',0);
	$forum_id = request_var('f',0);
	
	// Check forum id
	if(!$forum_id)
	{
		$sql = 'SELECT forum_id
			FROM ' . TOPICS_TABLE . "
			WHERE topic_id = $topic_id";
		$result = $db->sql_query($sql);
		$forum_id = (int) $db->sql_fetchfield('forum_id');
		$db->sql_freeresult($result);
	
		if (!$forum_id)
		{
			$_RESULT['success'] = false;
			die($user->lang['NO_TOPIC']);
		}
	}
	
	// Obtain first post in topic
	$sql_array = array(
		'SELECT'	=> 't.*, f.*, p.*',
	
		'FROM'		=> array(
			FORUMS_TABLE	=> 'f',
			TOPICS_TABLE	=> 't',
			POSTS_TABLE	=> 'p',
		),
		'WHERE'		=> "t.topic_id = $topic_id
			AND t.topic_first_post_id = p.post_id
			AND (f.forum_id = t.forum_id
				OR (t.topic_type = " . POST_GLOBAL . "
				AND f.forum_id = $forum_id))",
	);
	
	$sql = $db->sql_build_query('SELECT', $sql_array);
	$result = $db->sql_query($sql);
	$topic_data = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	
	// Check if such topic exists
	if (!$topic_data)
	{
		$_RESULT['success'] = false;
		die($user->lang['NO_TOPIC']);
	}
	
	// Check if we can read it
	if (!$auth->acl_get('f_read', $forum_id))
	{
		$_RESULT['success'] = false;
		die($user->lang['SORRY_AUTH_READ']);
	}
	
	if ($topic_data['forum_password'])
	{
		$sql = 'SELECT forum_id
			FROM ' . FORUMS_ACCESS_TABLE . '
			WHERE forum_id = ' . $forum_data['forum_id'] . '
				AND user_id = ' . $user->data['user_id'] . "
				AND session_id = '" . $db->sql_escape($user->session_id) . "'";
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
	
		if (!$row)
		{
			$_RESULT['success'] = false;
			die($user->lang['SORRY_AUTH_READ']);
		}
	}
	
	/*$server_path = generate_board_url() . '/';
	
	// Send vars to template
	$template->assign_vars(array(
		'TOPIC_ID' 		=> $topic_id,
		'TOPIC_TITLE' 	=> $topic_data['topic_title'],
		'TOPIC_POSTER'	=> $topic_data['topic_poster'],
	
		'TOPIC_AUTHOR_FULL'		=> get_username_string('full', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
		'TOPIC_AUTHOR_COLOUR'	=> get_username_string('colour', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
		'TOPIC_AUTHOR'			=> get_username_string('username', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
		'U_TOPIC'				=> "{$server_path}viewtopic.$phpEx?f=$forum_id&amp;t=$topic_id",
	));*/
	
	// Prepare post text for displaying
	
	// Instantiate BBCode if need be
	if ($topic_data['bbcode_bitfield'])
	{
		include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
		$bbcode = new bbcode($topic_data['bbcode_bitfield']);
	}
	
	$message = censor_text($topic_data['post_text']);
	
	// Second parse bbcode here
	if ($topic_data['bbcode_bitfield'])
	{
		$bbcode->bbcode_second_pass($message, $topic_data['bbcode_uid'], $topic_data['bbcode_bitfield']);
	}

	// Always process smilies after parsing bbcodes
	$message = bbcode_nl2br($message);
	$message = smiley_text($message);
	
	// Output post text
	echo $message;
}

/**
* Do the various checks required for removing posts as well as removing it
*/
function handle_post_delete($forum_id, $topic_id, $post_id, &$post_data)
{
	global $user, $db, $auth, $_RESULT;
	global $phpbb_root_path, $phpEx;

	include("$phpbb_root_path/includes/functions_posting.$phpEx");
	
	// If moderator removing post or user itself removing post, present a confirmation screen
	if ($auth->acl_get('m_delete', $forum_id) || ($post_data['poster_id'] == $user->data['user_id'] && $user->data['is_registered'] && $auth->acl_get('f_delete', $forum_id) && $post_id == $post_data['topic_last_post_id']))
	{
		$data = array(
			'topic_first_post_id'	=> $post_data['topic_first_post_id'],
			'topic_last_post_id'	=> $post_data['topic_last_post_id'],
			'topic_approved'		=> $post_data['topic_approved'],
			'topic_type'			=> $post_data['topic_type'],
			'post_approved'			=> $post_data['post_approved'],
			'post_reported'			=> $post_data['post_reported'],
			'post_time'				=> $post_data['post_time'],
			'poster_id'				=> $post_data['poster_id'],
			'post_postcount'		=> $post_data['post_postcount']
		);


		if ($post_data['topic_first_post_id'] == $post_data['topic_last_post_id'])
		{
			$_RESULT['success'] = false;
			exit($user->lang['CANNOT_DELETE_SINGLE_POST']);
		}
		else
		{
			$next_post_id = delete_post($forum_id, $topic_id, $post_id, $data);
			add_log('mod', $forum_id, $topic_id, 'LOG_DELETE_POST', $post_data['post_subject']);
		}

		exit($user->lang['POST_DELETED']."({$post_data['topic_first_post_id']};{$post_data['topic_last_post_id']})");
	}

	// If we are here the user is not able to delete - present the correct error message
	if ($post_data['poster_id'] != $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id))
	{
		$_RESULT['success'] = false;
		exit($user->lang['DELETE_OWN_POSTS']);
	}

	if ($post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id) && $post_id != $post_data['topic_last_post_id'])
	{
		$_RESULT['success'] = false;
		exit($user->lang['CANNOT_DELETE_REPLIED']);
	}

	$_RESULT['success'] = false;
	exit($user->lang['USER_CANNOT_DELETE']);
}
?>